import React, { Component } from 'react'
import { Card, Table, Button } from 'antd'
import { findCategroy } from '../../api/category'
import AddCat from './AddCat'

export default class Category extends Component {
  state = {
    data: [],
    parentId: 0,
  }
  componentDidMount() {
    this.getCategory()
  }
  // 获取所有分类
  getCategory = () => {
    let { parentId } = this.state
    findCategroy({ parentId }).then((res) => {
      this.setState({ data: res.data.data.data })
      // console.log(res.data.data)
    })
  }
  // 获取二级分类
  findSubsCategory = (v) => {
    findCategroy({ parentId: v._id }).then((res) => {
      this.setState({ data: res.data.data.data, parentId: v._id })
      // console.log(res.data.data)
    })
  }
  // 添加分类
  addCategory = () => {}
  // 返回上一级
  back = () => {
    this.setState(
      {
        parentId: 0,
      },
      () => {
        this.getCategory()
      }
    )
  }

  render() {
    const columns = [
      {
        title: '分类名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '分类类型',
        dataIndex: 'type',
        key: 'type',
      },
      {
        title: '操作',
        key: 'action',
        render: (values) => (
          <>
            {this.state.parentId == 0 ? (
              <Button
                onClick={() => this.findSubsCategory(values)}
                type="default"
              >
                查看子分类
              </Button>
            ) : null}
            &nbsp;&nbsp;&nbsp;
            <Button type="danger">删除</Button>
          </>
        ),
      },
    ]

    let { data } = this.state
    return (
      <>
        <Card
          title="产品分类"
          extra={
            <AddCat></AddCat>
            // <a onClick={this.addCategory} href="#">
            //   添加商品
            // </a>
          }
          style={{ width: '100%' }}
        >
          <Table
            scroll={{ y: '300px' }}
            rowKey={(v) => v._id}
            columns={columns}
            dataSource={data}
            bordered
            title={() =>
              this.state.parentId != 0 ? (
                <Button onClick={this.back}>返回上一级</Button>
              ) : null
            }
          />
        </Card>
      </>
    )
  }
}
